﻿using Microsoft.VisualBasic;
using Microsoft.VisualBasic.Logging;
using RouteConvertTool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace RouteConvertToolForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string kmzFilePath;
        private void button1_Click(object sender, EventArgs e)
        {
            //string filePath = @"d:\code_cpp\demos\ConsoleApp2\ConsoleApp2\waylines.wpml";
            string kmz_filePath = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置对话框的属性
                openFileDialog.Filter = "KMZ 文件 (*.kmz)|*.kmz"; // 限制只能选择 .kmz 文件
                openFileDialog.Title = "选择 KMZ 文件"; // 对话框标题
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 初始目录
                string tmpDir = @"H:\2025年工作\山东仿线02月-03月\鲁商凤凰广场航线";
                if (Directory.Exists(tmpDir))
                {
                    openFileDialog.InitialDirectory = tmpDir;
                }

                // 显示对话框
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    kmz_filePath = openFileDialog.FileName;

                    this.kmzFilePath = kmz_filePath;

                    // 在这里可以处理文件路径
                    //MessageBox.Show($"您选择的文件路径是：{filePath}", "文件选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("您取消了文件选择操作", "操作取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            string fileName = Path.GetFileNameWithoutExtension(kmz_filePath)+"_kmz解压";
            string dir = Path.GetDirectoryName(kmz_filePath);
            // 创建临时文件夹用于解压 KMZ 文件
            string tempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            tempFolder = Path.Combine(dir, fileName);
            Console.WriteLine("tempFolder:" + tempFolder);
            if (Directory.Exists(tempFolder)) 
            { 
                Directory.Delete(tempFolder, true);
            }
            Directory.CreateDirectory(tempFolder);

            // 解压 KMZ 文件
            ZipFile.ExtractToDirectory(kmz_filePath, tempFolder);

            // 查找并解析 WPML 文件
            string wpmlFile = Directory.GetFiles(tempFolder, "*.wpml", SearchOption.AllDirectories).FirstOrDefault();
            if (wpmlFile == null)
            {
                return;         
            }

            //wpmlFile = @"D:\code_cpp\demos\ConsoleApp2\ConsoleApp2\waylines.wpml";
            Console.WriteLine("wpmlFile:" + wpmlFile);

            XDocument doc = XDocument.Load(wpmlFile);

            // 定义命名空间
            XNamespace kml = "http://www.opengis.net/kml/2.2";
            XNamespace wpml = "http://www.dji.com/wpmz/1.0.6";

            var waypoints = doc.Descendants(kml + "Placemark")
                .Select(p => new WayPoint
                {
                    Index = int.Parse(p.Element(wpml + "index").Value),
                    ExecuteHeight = double.Parse(p.Element(wpml + "executeHeight").Value),
                    Longitude = double.Parse(p.Element(kml + "Point").Element(kml + "coordinates").Value.Split(',')[0].Trim()),
                    Latitude = double.Parse(p.Element(kml + "Point").Element(kml + "coordinates").Value.Split(',')[1].Trim()),
                    HeadingAngle = double.Parse(p.Element(wpml + "waypointHeadingParam").Element(wpml + "waypointHeadingAngle").Value),
                    GimbalPitchAngle = double.Parse(p.Element(wpml + "waypointGimbalHeadingParam").Element(wpml + "waypointGimbalPitchAngle").Value)
                })
                .OrderBy(w => w.Index)
                .ToList();

            string lineName = this.lineName_textBox1.Text;
            string towerNo = this.tower_no_textBox2.Text;

            List< WaypointX > waypointXes = new List< WaypointX >();
            foreach (var waypoint in waypoints)
            {
                WaypointX waypointX = new WaypointX();
                waypointX.SerialNo = waypoint.Index + 1;
                waypointX.Longitude = waypoint.Longitude;
                waypointX.Latitude = waypoint.Latitude;
                waypointX.AbsoluteHeight = waypoint.ExecuteHeight;
                waypointX.StartHeight = waypoint.ExecuteHeight - 10;

                waypointX.YawAngle = waypoint.HeadingAngle;
                waypointX.GimbalPitchAngle = waypoint.GimbalPitchAngle;

                waypointX.ComponentLatitude = waypoint.Latitude;
                waypointX.ComponentLongitude = waypoint.Longitude;
                waypointX.ComponentAltitude = waypoint.ExecuteHeight;


                {
                    double lat = waypoint.Latitude;
                    double lon = waypoint.Longitude;
                    UtmConverter.ConvertLatLonToUtm(lat, lon, out double easting, out double northing, out int zone);
                    waypointX.X = easting;
                    waypointX.Y = northing;

                  
                }
                if (waypointX.ComponentLatitude != null && waypointX.ComponentLongitude != null)
                {
                    double lat = waypointX.ComponentLatitude.Value;
                    double lon = waypointX.ComponentLongitude.Value;
                    UtmConverter.ConvertLatLonToUtm(lat, lon, out double easting, out double northing, out int zone);
                    waypointX.X = easting;
                    waypointX.Y = northing;
                    waypointX.ComponentX = easting;
                    waypointX.ComponentY = northing;
                }

                waypointX.ComponentTag = "转弯点";//转弯点 导线端挂点 锚点


                waypointX.LineName = lineName;
                waypointX.TowerNumber = towerNo;
                Console.WriteLine(waypoint);
                waypointXes.Add( waypointX );
            }

            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                // 设置对话框的属性
                saveFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 文件类型过滤
                saveFileDialog.DefaultExt = "xlsx"; // 默认文件扩展名
                saveFileDialog.AddExtension = true; // 自动添加扩展名
                saveFileDialog.FileName = "output"; // 默认文件名
                saveFileDialog.Title = "保存航线Excel文件"; // 对话框标题
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 初始目录
                saveFileDialog.InitialDirectory = dir;

                // 显示对话框
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    string savefilePath = saveFileDialog.FileName;

                    ExcelHelper.ExportToExcelFile(waypointXes, savefilePath);
                    Process.Start(savefilePath);

                    MessageBox.Show(this,$"航线文件已保存到：{savefilePath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("用户取消了保存操作", "操作取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

         

            
            //MessageBox.Show(this,"完成");

        }

        private void button_batch2kml_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
            {
                // 设置对话框的标题
                folderDialog.Description = "请选择一个文件夹";

                // 设置初始路径（可选）
                folderDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                // 设置是否显示新建文件夹按钮（可选）
                folderDialog.ShowNewFolderButton = true;

                // 显示对话框
                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件夹路径
                    string selectedFolder = folderDialog.SelectedPath;
                    convert2Kml(selectedFolder);

                    // 在这里可以对选中的文件夹路径进行处理
                    MessageBox.Show("选中的文件夹路径为: " + selectedFolder);
                }
            }
        }

        private void convert2Kml(String foler) 
        {
          

            // 获取目录下所有的.xlsx文件
            string[] xlsxFiles = Directory.GetFiles(foler, "*.xlsx", SearchOption.AllDirectories);


            string saveFileDir = Path.Combine(foler, "kml");
            if (!Directory.Exists(saveFileDir))
            {
                Directory.CreateDirectory(saveFileDir);
            }


            foreach (var xlsFile in xlsxFiles)
            {
                List<Waypoint> waypoints = ExcelParser.ParseExcelToWaypoints(xlsFile);

                // 打印结果以验证
                foreach (var waypoint in waypoints)
                {
                    Console.WriteLine($" {waypoint.No} Route Name: {waypoint.routeName}, Tower No: {waypoint.towerNo}, Latitude: {waypoint.Coordinates.Latitude}, Longitude: {waypoint.Coordinates.Longitude}, Altitude: {waypoint.Coordinates.Altitude}, Heading: {waypoint.Heading}, Component Type: {waypoint.ComponentType}");
                }

                // 获取用户选择的文件路径
                String kmlName = Path.GetFileNameWithoutExtension(xlsFile)+".kml";
                string savefilePath = Path.Combine(saveFileDir, kmlName);
                KmlGenerator.GenerateWaypointKML(savefilePath, waypoints,2,60);
            }
            MessageBox.Show(this, $"航线文件已保存到：{saveFileDir}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Process.Start(saveFileDir);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string xlsFilePath = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置对话框的属性
                openFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx"; // 限制只能选择 .xlsx 文件
                openFileDialog.Title = "选择 Excel 文件"; // 对话框标题
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 初始目录

                if (File.Exists(kmzFilePath))
                {
                    string dir = Path.GetDirectoryName(kmzFilePath);
                    openFileDialog.InitialDirectory = dir;
                }
                

                // 显示对话框
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    xlsFilePath = openFileDialog.FileName;



                    // 在这里可以处理文件路径
                    //MessageBox.Show($"您选择的文件路径是：{filePath}", "文件选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("您取消了文件选择操作", "操作取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }


            List<Waypoint> waypoints = ExcelParser.ParseExcelToWaypoints(xlsFilePath);

            // 打印结果以验证
            foreach (var waypoint in waypoints)
            {
                Console.WriteLine($" {waypoint.No} Route Name: {waypoint.routeName}, Tower No: {waypoint.towerNo}, Latitude: {waypoint.Coordinates.Latitude}, Longitude: {waypoint.Coordinates.Longitude}, Altitude: {waypoint.Coordinates.Altitude}, Heading: {waypoint.Heading}, Component Type: {waypoint.ComponentType}");
            }

            //foreach (var waypoint in waypoints)
            //{                
            //    Console.WriteLine($" {waypoint.No} , Latitude: {waypoint.ComponentLat}, Longitude: {waypoint.ComponentLon}, Altitude: {waypoint.ComponentAlt}");
            //}


            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                // 设置对话框的属性
                saveFileDialog.Filter = "kml 文件 (*.kml)|*.kml|所有文件 (*.*)|*.*"; // 文件类型过滤
                saveFileDialog.DefaultExt = "kml"; // 默认文件扩展名
                saveFileDialog.AddExtension = true; // 自动添加扩展名
                String fileName = Path.GetFileNameWithoutExtension(xlsFilePath);
                saveFileDialog.FileName = "output"; // 默认文件名
                saveFileDialog.FileName = fileName; // 默认文件名
                saveFileDialog.Title = "保存航线Excel文件"; // 对话框标题
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 初始目录
                if (File.Exists(xlsFilePath))
                {
                    string dir = Path.GetDirectoryName(kmzFilePath);
                    saveFileDialog.InitialDirectory = dir;
                }

      

                // 显示对话框
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    string savefilePath = saveFileDialog.FileName;


                    KmlGenerator.GenerateWaypointKML(savefilePath, waypoints);
                    Process.Start(savefilePath);

                    MessageBox.Show(this, $"航线文件已保存到：{savefilePath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("用户取消了保存操作", "操作取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string xlsFilePath = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                // 设置对话框的属性
                openFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx"; // 限制只能选择 .xlsx 文件
                openFileDialog.Title = "选择 Excel 文件"; // 对话框标题
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // 初始目录

                if (File.Exists(kmzFilePath))
                {
                    string dir = Path.GetDirectoryName(kmzFilePath);
                    openFileDialog.InitialDirectory = dir;
                }


                // 显示对话框
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    // 获取用户选择的文件路径
                    xlsFilePath = openFileDialog.FileName;



                    // 在这里可以处理文件路径
                    //MessageBox.Show($"您选择的文件路径是：{filePath}", "文件选择成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                else
                {
                    MessageBox.Show("您取消了文件选择操作", "操作取消", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }

            //xlsFilePath


        }

  
    }
}
